﻿(function ($) {
    if (!window.xbase) { window.xbase = {}; }
    window.xbase.doSearch = function (value, name) {
        $.messager.alert('You input', value + '(' + name + ')', 'info');
    }
    window.xbase.theme = function (themesName) {
        $('#themes').attr('href', '../themes/' + themesName + '/easyui.css');
        $.cookie('themesName', themesName, { expires: 7, });
    }
    window.xbase.urlparas = 'rnd=' + Math.random() + '&url=' + window.location.pathname;
    window.xbase.json = function (data) { return jQuery.parseJSON(data); }
    window.xbase.jsonPush = function (data) { var accInfos = []; return accInfos.push(data); } //单条记录：var accInfos = []; accInfos.push(jQuery.parseJSON(result).Web_Base_Account_Member_Parent); $('#dg_UserMore').datagrid('loadData', accInfos);
    window.xbase.refreshForm = function (btn, form, jsondata) { $(btn).click(function () { $(form).form('load', jsondata); }); }
    window.xbase.refreshDataGrid = function (btn, datagrid) { $(btn).click(function () { $(datagrid).datagrid('reload'); }); }
    window.xbase.closeDialog = function (btn, dialog) { $(btn).click(function () { $(dialog).dialog('close'); }); }
    window.xbase.openDialog = function (btnName, dialogName, href, title) { $(btnName).click(function () { $(dialogName).dialog({ title: title == null || title == '' ? '系统帮助' : title, method: 'get', closed: false, cache: false, href: href == null || href == '' ? '/html/tmp/AboutBlank.html' : href, modal: true, success: function (result) { alert(result); } }); }); };
    window.xbase.isNotNull = function (str) { return str != null; }
    window.xbase.isNotEmpty = function (str) { return (str != null && str != ""); }
    window.xbase.isNull = function (str) { return str == null; }
    window.xbase.isEmpty = function (str) { return (str == null || str == ""); }
    window.xbase.DialogStop = function (error, title, message) { if (error) { $.messager.alert(title, message); return false; } else return true; }
    window.xbase.loadRemote = function (form, url) { return $(form).form('load', url); }
    window.xbase.logonYes = function () {
        $.ajax({ /* 1.登录检测。【已登录，则自动进入Index.html页面】 */
            type: 'GET',
            url: '/ashx/App/LoginCheck.ashx',
            data: 'url=' + window.location.pathname + '&rnd=' + Math.random(),
            success: function (result) {
                var json = window.xbase.json(result);
                if (json.error == 0) {
                    window.location.href = './?' + Math.random();
                    return json.title;
                } else
                    return null;
            },
        });
    }
    window.xbase.logonNo = function (btnUser) {
        $.ajax({ /* 1.登录检测。【未登录，进入Login.html页面】 */
            type: 'GET',
            async: false,
            url: '/ashx/App/LoginCheck.ashx',
            data: 'url=' + window.location.pathname + '&rnd=' + Math.random(),
            success: function (result) {
                if (!(result != null && result != '')) return window.xbase.return('系统错误', 'Ajax返回空值，请稍后重试！<br />ps:如果您使用了360浏览器，请换之！', 'error');
                var json = window.xbase.json(result);
                if (json.error == 0) {
                    $(btnUser).linkbutton({ text: 'hi，' + json.title, });
                } else {
                    //$.messager.alert(json.title, json.message.m_StringValue, json.type);
                    window.location.href = 'login.html?rnd=' + Math.random();
                }
            },
        });
    }
    window.xbase.getDataGridItem = function (dg) {
        var row = $(dg).datagrid('getSelected');
        //$.messager.alert('Info', row.PkId + ":" + row.productname);
        return row ? row.PkId : 0;
    }
    window.xbase.getDataGridItems = function (dg) {
        var ss = [];
        var rows = $(dg).datagrid('getSelections');
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            ss.push(row.PkId);
        }
        //$.messager.alert('刷新', ss.join(','), 'info');
        return ss.join(',');
    }
    window.xbase.getTreeGridItem = function (tg) {
        var row = $(tg).treegrid('getSelected');
        //$.messager.alert('Info', row.PkId + ":" + row.productname);
        return row ? row.PkId : 0;
    }
    window.xbase.getTreeGridItems = function (tg) {
        var ss = [];
        var rows = $(tg).treegrid('getSelections');
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            ss.push(row.PkId);
        }
        //$.messager.alert('刷新', ss.join(','), 'info');
        return ss.join(',');
    }
    window.xbase.getTreeViewItem = function (tv) {
        var row = $(tv).tree('getSelected');
        //$.messager.alert('Info', row.PkId + ":" + row.productname);
        return row ? row.PkId : 0;
    }
    //window.xbase.loadRemote('#ff_userform', '/Ashx/Acc/Staff/AccInfoSale.ashx');
    window.xbase.FormatDate = function (val, row) {
        // ReSharper disable once ConditionIsAlwaysConst
        if (val == null || val == '' || val == undefined) return null;
        var date = new Date(val);
        return new Date(value).format("yyyy-MM-dd hh:mm:ss");
        return date.getFullYear() + '-' + window.xbase.zeroize(date.getMonth() + 1) + '-' + window.xbase.zeroize(date.getDate());
    }
    window.xbase.FormatDateTime = function (val, row) {
        var date = new Date(val);
        return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '.' + date.getMilliseconds();
    }
    window.xbase.formatDateTime = function (date) {
        return new Date(date).toLocaleString();
    }
    window.xbase.FormatParser = function (val, row) {
        if (!s) return new Date();
        var ss = (s.split('-'));
        var y = parseInt(ss[0], 10);
        var m = parseInt(ss[1], 10);
        var d = parseInt(ss[2], 10);
        if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
            return new Date(y, m - 1, d);
        } else {
            return new Date();
        }
    }
    window.xbase.zeroize = function (value, length) {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length) ; i++) {
            zeros += '0';
        }
        return zeros + value;
    };

    window.xbase.FormatDouble = function (val, row) {
        return val.toFixed(2);
    }
    window.xbase.FormatHrefAdmin = function (val, row) {
        if (val == null || val == '') return null;
        return '<a href="javascript:window.xbase.adminNodeView(' + row.PkId + ',' + row.ParentId + ');">进入</a>';
    }
    window.xbase.FormatUserFlagActive = function (val, row) {
        return row.FlagActive == 1 ? '是' : '否';
    }
    window.xbase.adminNodeView = function (id, pid) {
        $.messager.alert('Info:', 'id:' + id + ' - pid:' + pid, 'info');
    }
    window.xbase.FormatHrefParentNode = function (val, row) {
        var str = '查看';
        if (val == null || val == '') str = '无';
        return '<a href="javascript:window.xbase.parentNodeView(' + row.PkId + ',' + row.ParentId + ');">' + str + '</a>' + '【' + row.ParentId + '】';
    }
    window.xbase.parentNodeView = function (id, pid) {
        $.messager.alert('Info:', 'id:' + id + ' - pid:' + pid, 'info');
    }
    window.xbase.FormatUserFlagLevel = function (val, row) {
        switch (row.FlagLevel) {
            case 1:
                return '<em class="FlagLevelBronze">铜级</em>';
            case 2:
                return '<em class="FlagLevelSilver">银级</em>';
            case 3:
                return '<em class="FlagLevelGolden">金级</em>';
            case 4:
                return '<em class="FlagLevelGolden">钻级</em>';
            case 9:
                return '<em class="FlagLevelGolden">冠级</em>';
            default:
                return '<em class="FlagLevelBlank">空单</em>';
        }
    }
    window.xbase.FormatSaleFlagStatus = function (val, row) {
        switch (row.status) {
            case 9:
                return '停止';
            case 1:
                return '已审';
            case 0:
                return '未审';
            default:
                return '未知';
        }
    }
    window.xbase.FormatFlagPass = function (val, row) {
        switch (row.FlagPass) {
            case 9:
                return '停止';
            case 1:
                return '已审';
            case 0:
                return '未审';
            default:
                return '未知';
        }
    }
    window.xbase.FormatFlagView = function (val, row) {
        switch (row.FlagView) {
            case 1:
                return '显示';
            default:
                return '隐藏';
        }
    }
    window.xbase.FormatSalePassStatus = function (val, row) {
        switch (row.FlagPass) {
            case 9:
                return '停止';
            case 1:
                return '已审';
            case 0:
                return '未审';
            default:
                return '未知';
        }
    }
    window.xbase.FormatReply = function (val, row) {
        switch (row.count) {
            case 0:
                return '未回复';
            default:
                return '已回复';
        }
    }
    window.xbase.FormatUserFlagStatus = function (val, row) {
        switch (row.status) {
            case 1:
                return '<em class="FlagLevelBronze">正常</em>';
            case 6:
                return '<em class="FlagLevelGolden">白名</em>';
            case 7:
                return '<em class="FlagLevelGolden">黑名</em>';
            case -1:
                return '<em class="FlagLevelSilver">删除</em>';
            case 8:
                return '<em class="FlagLevelSilver">停止</em>';
            case 9:
                return '<em class="FlagLevelSilver">出局</em>';
            default:
                return '<em class="FlagLevelBlank">未知</em>';
        }
    }
    window.xbase.FormatPassTotal = function (val, row) {
        switch (row.total) {
            case 9:
                return '停止';
            case 1:
                return '已审';
            case 0:
                return '未审';
            default:
                return '未知';
        }
    }
    window.xbase.FormatPassCount = function (val, row) {
        switch (row.count) {
            case 9:
                return '停止';
            case 1:
                return '已审';
            case 0:
                return '未审';
            default:
                return '未知';
        }
    }
    window.xbase.getQuery = function (q, p, o) {
        var s = q != null && q != '' && o != null && o != '' ? '&' : '';
        return o != null && o != '' ? s + p + '=' + o : '';
    }
    window.xbase.checkDataGridItems = function (dg) {
        var items = window.xbase.getDataGridItems(dg);
        if (items == null || items == '' || items.split(',').length == 0) {
            $.messager.alert('选项错误', '在表格中至少选择一行', 'error');
            return false;
        } else {
            return true;
        }
    }
    window.xbase.checkDataGridItemNew = function (dg) {
        var roots = $(dg).datagrid('getRows');
        if (roots == null || roots == '') {
            // 创建根
            return true;
        } else {
            // 创建其它
            return window.xbase.checkDataGridItem(dg);
        }
    }
    window.xbase.checkDataGridItem = function (dg) {
        var items = window.xbase.getDataGridItems(dg);
        if (items == null || items == '' || items.split(',').length != 1) {
            $.messager.alert('选项错误', '在表格中只能且必须选择一行', 'error');
            return false;
        } else {
            return true;
        }
    }
    window.xbase.checkTreeViewNode = function (tree) {
        var nodes = $(tree).tree('getSelected');
        if (nodes != null && nodes != '') {
            return true;
        } else {
            $.messager.alert('选项错误', '只能且必须选择一个树节点', 'error');
            return false;
        }
    }
    window.xbase.checkTreeViewId = function (tree) {
        var nodes = $(tree).tree('getSelected');
        if (nodes != null && nodes != '') {
            return nodes.id;
        } else {
            return 0;
        }
    }
    window.xbase.checkTreeViewLeaf = function (tree) {
        var nodes = $(tree).tree('getSelected');
        if ($(tree).tree('isLeaf', nodes.target))
            return true;
        else {
            $.messager.alert('选项错误', '只能选择叶节点（最终节点）', 'error');
            return false;
        }
    }
    window.xbase.selectCombobox = function (obj, url, v) {
        $(obj).combobox({
            url: url,
            valueField: 'id',
            textField: 'text',
            //value: '0',
            onSelect: function (record) {
                //$("#users").val(record.ID);
            },
            onLoadSuccess: function () {
                var items = $(this).combobox("getData");
                if (v == null || v == '' || v == undefined) {
                    $(this).combobox("select", items[0].id);
                }
                else {
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].id == v) $(this).combobox("select", items[i].id);
                    }
                }
            },
        });
    }
    window.xbase.setItemID = function (dg) {
        alert(dg);
        //$("#GridItemsID").attr("value", window.xbase.getDataGridItems('#dg_object'));//已经作废
    }
    window.xbase.submitForm = function (form, url) {
        $(form).form('submit', {
            url: url,
            onSubmit: function () {
                if (!$(this).form('validate'))
                    return false;
                else
                    return true;
            },
            success: function (data) {
                var json = jQuery.parseJSON(data);
                if (json.error == 0)
                    $.messager.alert('操作提示', json.message.m_StringValue, 'info');
                else
                    $.messager.alert('操作错误', json.message.m_StringValue, 'error');
                //document.location.reload(true);
                //window.xbase.loadRemote('#ff', '/Ashx/Acc/Staff/AccInfoSale.ashx');
            },
        });
    }
    window.xbase.submitAjaxGet = function (url, data) {
        $.ajax({
            type: 'GET',
            url: url,
            data: data,
            success: function (result) {
                return result;
            },
        });
    }
    window.xbase.openit = function (title, plugin) {
        //debugger;
        if ($('#tt').tabs('exists', title)) {
            $('#tt').tabs('select', title);
        } else {
            var tabs = $("#tt").tabs("tabs");
            if (tabs.length > 1) $("#tt").tabs("close", tabs[1].panel('options').tab.text());

            $('#tt').tabs('add', {
                title: title,
                href: plugin,
                closable: true,
                extractor: function (data) {
                    data = $.fn.panel.defaults.extractor(data);
                    /// var tmp = $('<div></div>').html(data);
                    /// data = tmp.find('#content').html();
                    /// tmp.remove();
                    return data;
                }
            });
        }
    }
    window.xbase.return = function(title, info, error)
    {
        $.messager.alert(title, info, error);
        return false;
    }
    function getSelected() {
        var row = $('#dg').datagrid('getSelected');
        if (row) $.messager.alert('Info', row.PkId + ":" + row.productname);
    }
    function getSelections() {
        var ss = [];
        var rows = $('#dg').datagrid('getSelections');
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            ss.push('<span>' + row.PkId + ":" + row.PkId + '</span>');
        }
        $.messager.alert('确定要删除这些记录吗？', ss.join('<br/>', 'info'));
    }
    $.extend($.fn.datetimebox.defaults, {
        formatter: function (date) {
            var h = date.getHours();
            var M = date.getMinutes();
            var s = date.getSeconds();
            var ampm = h >= 12 ? 'pm' : 'am';
            h = h % 12;
            h = h ? h : 12;
            function formatNumber(value) {
                return (value < 10 ? '0' : '') + value;
            }
            var separator = $(this).datetimebox('spinner').timespinner('options').separator;
            var r = $.fn.datebox.defaults.formatter(date) + ' ' + formatNumber(h) + separator + formatNumber(M);
            if ($(this).datetimebox('options').showSeconds) {
                r += separator + formatNumber(s);
            }
            r += ' ' + ampm;
            return r;
        },
        parser: function (s) {
            if ($.trim(s) == '') {
                return new Date();
            }
            var dt = s.split(' ');
            var d = $.fn.datebox.defaults.parser(dt[0]);
            if (dt.length < 2) {
                return d;
            }
            var separator = $(this).datetimebox('spinner').timespinner('options').separator;
            var tt = dt[1].split(separator);
            var hour = parseInt(tt[0], 10) || 0;
            var minute = parseInt(tt[1], 10) || 0;
            var second = parseInt(tt[2], 10) || 0;
            var ampm = dt[2];
            if (ampm == 'pm') {
                hour += 12;
            }
            return new Date(d.getFullYear(), d.getMonth(), d.getDate(), hour, minute, second);
        }
    });
})(jQuery);
var Common = {
    //EasyUI用DataGrid用日期格式化
    TimeFormatter: function (value, rec, index) {
        if (value == undefined) {
            return "";
        }
        /*json格式时间转js时间格式*/
        value = value.substr(1, value.length - 2);
        var obj = eval('(' + "{Date: new " + value + "}" + ')');
        var dateValue = obj["Date"];
        if (dateValue.getFullYear() < 1900) {
            return "";
        }
        var val = dateValue.format("yyyy-mm-dd HH:MM");//控制格式
        return val.substr(11, 5);
    }
};